package net.util.NioHttpClient;

import java.io.IOException;
import java.net.SocketException;
import java.net.StandardSocketOptions;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public abstract class NioHttpConnection {
    private final Map<String, String> HttpHeaders;
    private final LinkedList<ByteBuffer> payloadFragments;
    private int responseCode;
    private String responseMessage;
    private URL url;
    private SocketChannel channel;
    private String requestMode;
    private final StringBuilder arbitraryStringBuilder;
    private boolean dataReady;

    protected String generateHttpRequestHeader() {
        this.arbitraryStringBuilder.setLength(0);
        this.arbitraryStringBuilder.append(this.requestMode).append(' ').append(url.getPath()).append(' ').append("HTTP/1.1\r\n");
        this.arbitraryStringBuilder.append("HOST: ").append(url.getHost()).append("\r\n");
        for(Entry<String, String> headerElement : HttpHeaders.entrySet()) {
            this.arbitraryStringBuilder.append(headerElement.getKey()).append(": ").append(headerElement.getValue()).append("\r\n");
        }
        this.arbitraryStringBuilder.append("\r\n");
        return this.arbitraryStringBuilder.toString();
    }

    public NioHttpConnection() throws IOException {
        this.HttpHeaders = new LinkedHashMap<String, String>();
        this.payloadFragments = new LinkedList<ByteBuffer>();
        this.channel = SocketChannel.open();
        this.arbitraryStringBuilder = new StringBuilder();
        this.dataReady = false;
    }

    public SelectableChannel configureBlocking(boolean blocking) throws IOException {
        return this.channel.configureBlocking(blocking);
    }
    
    public String getRequestMode(){
        return this.requestMode;
    }

    public int getResponseCode() {
        return this.responseCode;
    }
    
    public String getResponseMessage() {
        return this.responseMessage;
    }
 
    public void setRequestMode(String mode) {
        this.requestMode = mode;
    }

}
